package main
import(
	"http"
	"io/ioutil"
	"json"
	"system"
	"fmt"
	"container/list"
	"bytes"
	"path/filepath"
	"os"
	"image"
	"image/png"
	"encoding/base64"
)
/*
处理url请求
*/
func ThumbnailsHandler(response http.ResponseWriter,r *http.Request){
	err:=r.ParseForm()
	if LogError(err){
		response.WriteHeader(http.StatusBadRequest)
		return
	}
	value:=r.Form
	p,_:=base64.URLEncoding.DecodeString(value.Get("q"))
	path:=string(p)
	file,err:=os.Open(path)
	defer file.Close()
	if LogError(err){
		response.WriteHeader(http.StatusInternalServerError)
		return
	}

	img,_,err:=image.Decode(file)
	if LogError(err){
		response.WriteHeader(http.StatusInternalServerError)
		return
	}
	w,h:=img.Bounds().Dx(),img.Bounds().Dy()
	width:=200
	coe:=float64(width)/float64(w)
	height:=int(float64(h)*coe)
	img2:=image.NewNRGBA(width,height)

	for x:=1;x<=width;x++{
		for y:=1;y<height;y++{
			x1:=int(float64(x)/coe)
			y1:=int(float64(y)/coe)
			c:=img.At(x1,y1)
			img2.Set(x,y,c)
		}
	}
	png.Encode(response,img2)
	img=nil
	img2=nil
	onRequest()
}
func GetPropertyHandler(w http.ResponseWriter,r *http.Request){
	err:=r.ParseForm()
	if LogError(err){
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	value:=r.Form
	intendsByte:=bytes.Split([]byte(value.Get("q")),[]byte(" "))
	list:=list.New()
	for _,s := range intendsByte{
		list.PushBack(string(s))
	}
	buffer,err:=json.Marshal(system.GetProperty(list))
	if(LogError(err)){
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type","text/json")
	w.Write(buffer)
	onRequest()
}
//请求获取文件信息
func GetFileHandler(w http.ResponseWriter,r *http.Request){
	err:=r.ParseForm()
	if LogError(err){
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	value:=r.Form
	p,err:=base64.StdEncoding.DecodeString(value.Get("q"))
	LogError(err)
	path:=string(p)
	var b []byte
	b=append(b,os.PathListSeparator)
	strings:=bytes.Split([]byte(path),b)
	var list []interface{}
	for _,s:=range strings{
		f:=system.GetFileInfo(string(s))
		list=append(list,f)
	}
	buffer,err:=json.Marshal(list)
	if LogError(err){
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte(err.String()))
		return
	}
	w.Header().Set("Content-Type","text/json")
	w.Write(buffer)
	onRequest()
}
//下载文件
func DownloadHandler(w http.ResponseWriter,r *http.Request){
	err:=r.ParseForm()
	if LogError(err){
		http.Error(w,err.String(),http.StatusBadRequest)
		return
	}
	p,err:=base64.StdEncoding.DecodeString(r.Form.Get("q"))
	LogError(err)
	path:=string(p)
	if path==""{return}
	buffer,err:=ioutil.ReadFile(path)
	if LogError(err){
		http.Error(w,err.String(),http.StatusInternalServerError)
		return
	}else{
		filename:=filepath.Base(path)
		w.Header().Set("Content-Type",system.GetContentType(path))
		w.Header().Set("Content-Length",fmt.Sprint(len(buffer)))
		w.Header().Set("Content-disposition","attachment;filename="+filename)
		w.Write(buffer)
	}
	onRequest()
}
func RootHandler(w http.ResponseWriter,r *http.Request){
	path:=r.URL.Path
	err:=r.ParseForm()
	if(LogError(err)){
		http.Error(w,err.String(),http.StatusBadRequest)
		return

	}
	if(path=="/"||path==""){
		path="/"+Config.Index
	}
	if s:=[]byte(path);bytes.HasSuffix(s,[]byte("/")){
		index:=len(s)
		s=s[:index-1]
		path=string(s)
	}
	buffer,err:=ioutil.ReadFile(Config.HTML+path)
	if LogError(err){
		http.Error(w,err.String(),http.StatusNotFound)
	}else{
		contentType:=system.GetContentType(path)
		w.Header().Set("Content-Type",contentType)
		w.Write(buffer)
	}
	onRequest()
}
//在response中写入错误页面
func writeErrorPage(w http.ResponseWriter,httpStatus int){
	w.WriteHeader(httpStatus)
	buffer,err:=ioutil.ReadFile(Config.HTML+"/error/"+fmt.Sprint(httpStatus)+".html")
	if(LogError(err)){
		http.Error(w,err.String(),http.StatusInternalServerError)
		return
	}
	w.Write(buffer)
}
func onRequest(){
	RequestCount++
	OnRequestChan<-RequestCount
}
